<?php

class InstallmentController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action admroller here */
        $this->list_sess_unset('controller_installment');
        $this->session_search_key = 'controller_installment';
        $this->session_search_name = 'search_label';
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'installment', '');
    }

    public function viewAction() {
        if ($this->_getParam('ins_id') && $this->_getParam('ins_id') != "") {
            $ins_id = $this->_getParam('ins_id');
        } else {
            $this->_helper->redirector('list', 'installment', '');
        }
        $installmentModel = new Model_Installment();
        $installmentdata = $installmentModel->fetchEntryByViewId($ins_id);
        $this->view->installmentdata = $installmentdata;
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "";
        $searchtype = "";
        $searchtext = "";
        $searchtext_fromdate = "";
        $searchtext_todate = "";
        $orderField = 'ins_id';
        $sort = 'asc';
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
          $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext'] = '';  
          $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] ['searchtype']= "";
          $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate'] = "";
          $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate'] = "";
        
        }
        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;

        //PAGING_PER_PAGE
        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }
        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();

            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = ' Please select atleast one checkbox! ';
                }
            }

            /* Search Facility Over Here */
            /* if ($postedData["searchtype_startdate"] == "") {
              $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['startdate'] = "";
              }
              if ($postedData["searchtype_enddate"] == "") {
              $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['enddate'] = "";
              } */

            if ($postedData["searchtype"] == '') {
                $errorMessage[] = "Please select option.";
            }
            if ($postedData["searchtype"]) {
                $searchtype = $postedData["searchtype"];
                /* Installment NAME */
                if ($searchtype == 'ln_name') {
                     $searchtext = $postedData["searchtext_loan"];
                    if ($searchtext != '') {
                        $where = $searchtype . " like '%" . $searchtext . "%'";
                    } else {
                        $errorMessage[] = "Please enter search text.";
                    }
                }

                /* Customer Name */
                if ($searchtype == 'cus_name') {
                    $searchtext = $postedData["searchtext_customer"];
                    if ($searchtext != '') {
                        $where = $searchtype . " like '%" . $searchtext . "%'";
                    } else {
                        $errorMessage[] = "Please enter search text.";
                    }
                }

                /* Start Date */
                if ($searchtype == 'ins_creditdate') {
                     $searchtext_fromdate = $postedData["searchtext_creditfromdate"];
                     $searchtext_todate = $postedData["searchtext_credittodate"];
                   if($searchtext_fromdate!='' && $searchtext_todate!=''){
                       $where = "ins_creditdate BETWEEN  '" . $searchtext_fromdate . "' AND '" . $searchtext_todate . "'";
                    
                    }else{
                        $errorMessage[] = "Please select date.";
                    }
                }

                /* End Date */
                if ($searchtype == 'ins_uptodate') {
                    $searchtext_fromdate = $postedData["searchtext_uptofromdate"];
                    $searchtext_todate = $postedData["searchtext_uptotodate"];
                   if($searchtext_fromdate!='' && $searchtext_todate!=''){
                       $where = "ins_uptodate BETWEEN  '" . $searchtext_fromdate . "' AND '" . $searchtext_todate . "'";
                    
                    }else{
                        $errorMessage[] = "Please select date.";
                    }
                }
                
                
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = $searchtype;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext'] = $searchtext;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate'] = $searchtext_fromdate;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate'] = $searchtext_todate;

                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
                $this->view->searchtext = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext'];
                $this->view->searchtext_fromdate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate'];
                $this->view->searchtext_todate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate'];
            }
        } else {
            /* if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
              $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = '';
              } */
            $searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
            $searchtext = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext'];
            $searchtext_fromdate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate'];
            $searchtext_todate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate'];

            /* installment NAME */
            if ($searchtype == 'ln_name') {
                if ($searchtext != '') {
                    $where = $searchtype . " like '%" . $searchtext . "%'";
                } else {
                    $errorMessage[] = "Please enter search text.";
                }
            }

            /* Customer Name */
            if ($searchtype == 'cus_name') {
                if ($searchtext != '') {
                    $where = $searchtype . " like '%" . $searchtext . "%'";
                } else {
                    $errorMessage[] = "Please enter search text.";
                }
            }

           

           /* credit Date */
                if ($searchtype == 'ins_creditdate') {
                   if($searchtext_fromdate!='' && $searchtext_todate!=''){
                       $where = "ins_creditdate BETWEEN  '" . $searchtext_fromdate . "' AND '" . $searchtext_todate . "'";
                    
                    }else{
                        $errorMessage[] = "Please select date.";
                    }
                }

                /* upto Date */
                if ($searchtype == 'ins_uptodate') {
                   if($searchtext_fromdate!='' && $searchtext_todate!=''){
                       $where = "ins_uptodate BETWEEN  '" . $searchtext_fromdate . "' AND '" . $searchtext_todate . "'";
                    
                    }else{
                        $errorMessage[] = "Please select date.";
                    }
                }

                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = $searchtype;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext'] = $searchtext;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate'] = $searchtext_fromdate;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate'] = $searchtext_todate;

                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
                $this->view->searchtext = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext'];
                $this->view->searchtext_fromdate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate'];
                $this->view->searchtext_todate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate'];
           }

        $installmentModel = new Model_Installment();
        $installmentData = $installmentModel->fetchInstallment($where, $itemsPerPageReviews, $offset, $orderField, $sort);
        
        
        
        
        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($installmentModel->getInstallmentCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'installment', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->installmentData = $installmentData;
        
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $installmentModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function deleteAction($ids = Array()) {
        //Load installment Model 
        $installmentModel = new Model_Installment();
        if ($this->_getParam('ins_id') && $this->_getParam('ins_id') != "") {
            $ins_id = $this->_getParam('ins_id');
            $installmentModel->deleteInstallment($ins_id);
            $this->addSuccessMessage('Record Successfully Deleted');
            $this->_helper->redirector('list', 'installment', '');
        } else {
            $installmentModel->deleteInstallment($ids);
            $this->addSuccessMessage('Record Successfully Deleted');
            $this->_helper->redirector('list', 'installment', '');
        }
    }

    public function formAction() {

        //Initialize variables
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $installmentData = Array();
        $this->view->mode = "Add";

        //Load installment Model
        $installmentModel = new Model_Installment();

        
        //Load installment Form
        $installmentForm = new Form_InstallmentForm();

        

        //Load the status array for the select box in form 
        $statusArray = $installmentModel->getStatusArray();
        $installmentForm->ins_status->addMultiOptions($statusArray);

        

        //Check for the installment Parameter
        $installmentData['ins_id'] = $this->_request->getParam('ins_id');
        $ins_id = (!empty($installmentData['ins_id'])) ? $installmentData['ins_id'] : null;

        //check loan id
        $installmentData['ins_ln_id'] = $this->_request->getParam('ln_id');
        $ins_ln_id = (!empty($installmentData['ins_ln_id'])) ? $installmentData['ins_ln_id'] : null;
        
        $loanWhere = "";
        $customerWhere = "";
        $LoanModel = new Model_Loan();
        if (!empty($ins_ln_id)) {
            //Load installment Model
           // $LoanModel = new Model_Loan();
            $loan_data = $LoanModel->fetchEntryById($ins_ln_id);
            

            if ($loan_data) {
                $loanWhere = "ln_id = '" . $ins_ln_id . "'";
                $customerWhere = "cus_id = '" . $loan_data['ln_cus_id'] . "'";
                $data['ins_ln_id'] = $loan_data['ln_id'];
                $data['ins_cus_id'] = $loan_data['ln_cus_id'];
            }
            //Load the customer array for the select box in form 
            
        }
        
         if (!empty($ins_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $installmentModel->fetchEntryById($ins_id);
            $customerWhere = "cus_id = '" . $data['ins_cus_id'] . "'";
            
        }
        
        
        $customerArray = $installmentModel->getcustomerArray($customerWhere);
        $installmentForm->ins_cus_id->addMultiOptions($customerArray);
        
        
        //Load the loan array for the select box in form 
        $loanArray = $installmentModel->getloanArray($loanWhere);
        $installmentForm->ins_ln_id->addMultiOptions($loanArray);
        
       

        //Populate form 
        $this->view->form = $installmentForm->populate($data);
        if ($this->getRequest()->isPost()) {

            //Check for Errors
            $postedData = $this->_request->getPost();
			
			if($postedData['ins_ln_id'] != ''){
                            $ins_ln_id = $postedData['ins_ln_id'];
                            $loan_data = $LoanModel->fetchEntryById($ins_ln_id);
                            if ($loan_data) {
                                    $customerWhere = "cus_id = '" . $loan_data['ln_cus_id'] . "'";
                            }
                            $customerArray = $installmentModel->getcustomerArray($customerWhere);
                            $installmentForm->ins_cus_id->addMultiOptions($customerArray);
			}
            if (!$installmentForm->isValid($postedData)) {
                $errorMessage = $installmentForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
                if (count($errorMessageArray) > 0) {
                    
                } else {
                    if ($this->view->mode == "Add") {
                        $installmentData['ins_createddate'] = date("Y-m-d H:i:s");
                    }

                    //Installment save
                    $installmentData['ins_id'] = $ins_id;
                    $installmentData['ins_ln_id'] = $postedData['ins_ln_id'];
                    $installmentData['ins_cus_id'] = $postedData['ins_cus_id'];
                    $installmentData['ins_amount'] = $postedData['ins_amount'];
                    $installmentData['ins_creditdate'] = $postedData['ins_creditdate'];
                    $installmentData['ins_uptodate'] = $postedData['ins_uptodate'];
                    $installmentData['ins_updateddate'] = date("Y-m-d H:i:s");
                    $installmentData['ins_note'] = $postedData['ins_note'];
                    $installmentData['ins_status'] = $postedData['ins_status'];
                    $installmentModel->save($installmentData, 'ins_id');

                    if ($this->view->mode == "Add") {
                        $successmessage = 'Installment added successfully';
                    } else {
                        $successmessage = 'Installment updated successfully';
                    }

                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'installment', '');
                }
            }
        }
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $installmentForm;
    }

    
    //ajax resp for customerList in dropdown
   
    public function customerarraylistAction() {
        $listString = "";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $installmentModel = new Model_Installment();
            $LoanModel = new Model_Loan();
            $ins_ln_id = $postedData['ins_ln_id'];
            $loan_data = $LoanModel->fetchEntryById($ins_ln_id);
            if ($loan_data) {
                    $customerWhere = "cus_id = '" . $loan_data['ln_cus_id'] . "'";
            }
            $jsonString = "";
            //Load the customer array for the select box in form 
            $customerArray = $installmentModel->getcustomerArray($customerWhere);
            if ($customerArray) {
                //print_r($customerArray);
                $jsonString ="<select name='ins_cus_id' id='ins_cus_id'>";
                foreach($customerArray as $key => $_cust) {
                    //print_r($_cust);
                    $jsonString .= "<option value = '".$key ."'>".$_cust."</option>";
                }
                $jsonString .="</select>";
               // exit;
            }
            
        }
      echo $jsonString;
      exit;
    }
    
   
    
    
}

?>